package com.bank.filer;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import com.bank.util.SessionUtils;
import com.bank.base.*;
public class LoginCertifyFilter implements Filter{
	
		Logger logger = Logger.getLogger(LoginCertifyFilter.class);
	
	String loginPage=null;
	public void init(FilterConfig arg0) throws ServletException {
		loginPage = arg0.getInitParameter("login-page");
	}

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		// doFilter方法的第一个参数为ServletRequest对象。
		// 此对象给过滤器提供了对进入的信息（包括表单数据、cookie和HTTP请求头）的完全访问。
		// 第二个参数为ServletResponse，通常在简单的过滤器中忽略此参数。
		// 最后一个参数为FilterChain，此参数用来调用servlet或JSP页。
		
		HttpServletRequest httpRequest = (HttpServletRequest) request;
		HttpServletResponse httpResponse = (HttpServletResponse) response;
		String currentURL = httpRequest.getRequestURI();
		int start = currentURL.indexOf("/", 1);
		int end = currentURL.indexOf(".", 1);
		String targetURL = currentURL.substring(start < 0 ? 0 : start, end < 0 ? currentURL.length() : end);
		String name = (String) SessionUtils.getSessionUserName(httpRequest);
		logger.debug("url="+targetURL);
		if(name==null){
			if(targetURL.equals("/login")||targetURL.equals("/doLogin")){
				logger.debug("无需检查直接跳转至login.jsp");
				//获取最新工作日期
				chain.doFilter(request, response);
			}else
			{
				logger.debug("没有登录直接跳转到login.jsp");
				httpResponse.sendRedirect(httpRequest.getContextPath()+"/login.do"); 
			}
		}else{
			RequestSupport.setLocalRequest((HttpServletRequest) request);
			if(targetURL.equals("/login")||targetURL.equals("/doLogin")){
				logger.debug("已登录直接跳转到index.jsp");
				httpResponse.sendRedirect(httpRequest.getContextPath()+"/index.do"); 
			}else
			{
				logger.debug("已登录直接跳转到使用原界面"+targetURL);
				chain.doFilter(request, response);
			}
			
		}	
		
	}
	
}
